<template>
    <div class="app-container">
        <div class="filter-container">
            <div class="inline-left">
                <p>用户电话：</p>
                <el-input
                    v-model="listQuery.phone"
                    placeholder="电话"
                    size="medium"
                    style="width: 200px"
                    @keyup.enter.native="handleFilter"
                />
            </div>
            <div class="inline-left">
                <p>用户类型：</p>
                <el-select
                    v-model="listQuery.type"
                    placeholder="类型"
                    clearable
                    style="width: 130px"
                >
                    <el-option
                        v-for="item in calendarTypeOptions"
                        :key="item.key"
                        :label="item.display_name + '(' + item.key + ')'"
                        :value="item.key"
                    />
                </el-select>
            </div>

            <div class="inline-left">
                <el-button
                    v-waves
                    type="primary"
                    icon="el-icon-search"
                    @click="handleFilter"
                >
                    搜索
                </el-button>
            </div>

            <div class="inline-left">
                <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleCreate"
                >
                    添加
                </el-button>
            </div>

            <div class="inline-left">
                <el-button
                    v-waves
                    :loading="downloadLoading"
                    type="primary"
                    icon="el-icon-download"
                    @click="handleDownload"
                >
                    导出
                </el-button>
            </div>
        </div>
        <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
        >   
            <el-table-column
                v-for="item in tableLabel"
                align="center"
                :label="item.label"
                :prop="item.id"
                :width="item.width"
            />
        </el-table>
    </div>
</template>

<script>
// import { getList } from '@/api/table'
import { sendGetRequest } from "@/request/request";
import { parseTime } from '@/utils'
import XLSX from 'xlsx'
export default {
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: "success",
                draft: "gray",
                deleted: "danger"
            };
            return statusMap[status];
        }
    },
    data() {
        return {
            list: null,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                importance: "",
                phone: "",
                type: "",
                sort: "+id"
            },
            tableLabel:[
                {
                    label:'用户id',
                    id:'id',
                    width:'150'
                },
                {
                    label:'用户昵称',
                    id:'nickname',
                },

                {
                    label:'手机号',
                    id:'phone',
                    width:'150'
                },
                {
                    label:'积分',
                    id:'integral',
                    width:'150'
                },
                {
                    label:'总消费金额',
                    id:'money',
                    width:'200'
                },
                {
                    label:'总消费次数',
                    id:'number',
                    width:'200'
                },
                {
                    label:'注册时间',
                    id:'created',
                    width:'200'
                },
            ]
        };
    },
    created() {
        this.fetchData();
    },
    methods: {
        fetchData() {
            this.listLoading = true;
            this.sendGetRequest(this.api.userList, {
                page_size: 20,
                size: 1,
                status: 1
            }).then(res => {
                this.list = res.list;
                this.listLoading = false;
            });
        },
        // // 导出
        handleDownload() {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            //  let newArr = Object.keys(this.list[0])  
            const tHeader = this.tableLabel.map(res=>res.label)
            const filterVal = this.tableLabel.map(res=>res.id)
            const data = this.formatJson(filterVal)
           const multiHeader =[['主要信息',null,null,null,null,null,"时间"]]
            // console.log(data);
            const merges =[
                // 设置A1-C1的单元格合并
                // 开始坐标 结束坐标
                "A1:F1"
            ];
            excel.export_json_to_excel({
              multiHeader:multiHeader,
              header: tHeader,
              data,
              filename: 'table-list',
              merges:merges
            })
            this.downloadLoading = false
          })
        },
        // 导出
        // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
         sheet2blob(sheet, sheetName) {
            sheetName = sheetName || 'sheet1';
            var workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            };
            workbook.Sheets[sheetName] = sheet;
            // 生成excel的配置项
            var wopts = {
                bookType: 'xlsx', // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                type: 'binary'
            };
            var wbout = XLSX.write(workbook, wopts);
            var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
            // 字符串转ArrayBuffer
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
            return blob;
        },
        /**
         * 通用的打开下载对话框方法，没有测试过具体兼容性
         * @param url 下载地址，也可以是一个blob对象，必选
         * @param saveName 保存文件名，可选
         */
        openDownloadDialog(url, saveName)
        {
            if(typeof url == 'object' && url instanceof Blob)
            {
                url = URL.createObjectURL(url); // 创建blob地址
            }
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if(window.MouseEvent) event = new MouseEvent('click');
            else
            {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        },
        // handleDownload() {
        //     //表头
        //     const tHeader = this.tableLabel.map(res=>res.label)
        //     //表头对应的字段
        //     const filterVal = this.tableLabel.map(res=>res.id)
        //     const data = this.formatJson(filterVal)

        //     // data头部追加表头
        //     data.unshift(tHeader)
        //     data.unshift(['主要信息',null,null,null,null,"时间"])
        //     // 生成表格切片
        //     var sheet = XLSX.utils.aoa_to_sheet(data);
            
        //     console.log(sheet);
        //     sheet['!merges'] = [
        //         // 设置A1-C1的单元格合并
        //         {s: {r: 0, c: 0}, e: {r: 0, c: 2}},
        //         {s: {r: 2, c: 1}, e: {r: 3, c: 1}}
        //     ];
        //     this.openDownloadDialog(this.sheet2blob(sheet), '导出.xlsx');
        // },
        // 在这里可以处理的某一个特殊字段
        formatJson(filterVal) {
          // 遍历list 数组的每一项
          return this.list.map(v =>
          // 遍历出需要导出的字段形成一个数组
            filterVal.map(j => v[j] )
          )
        },
    }
};
</script>

<style lang="scss" scoped>
.filter-container {
    // padding-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
    .inline-left {
        display: flex;
        align-items: center;
        margin-right: 15px;
        margin-bottom: 10px;
        p{
            font-size: 15px;
        }
    }
}
</style>
